<template>
	<xn-form-container
		:title="formData.id ? '编辑设备预约' : '增加设备预约'"
		:width="700"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="预约日期：" name="reservationDate">
						<a-date-picker
							v-model:value="formData.reservationDate"
							value-format="YYYY-MM-DD"
							style="width: 100%"
							placeholder="请选择预约日期"
							:disabled-date="disabledDate"
							@change="handleDateChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备类型：" name="typeId">
						<a-select
							v-model:value="formData.typeId"
							placeholder="请选择设备类型"
							:options="typeOptions"
							@change="handleTypeChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="预约时间段：" name="timeSlot">
						<a-select
							v-model:value="formData.timeSlot"
							placeholder="请选择预约时间段"
							:disabled="!formData.reservationDate || !formData.typeId"
							:options="timeSlotOptions"
							@change="handleTimeSlotChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备名称：" name="deviceName">
						<a-select
							v-model:value="formData.deviceName"
							placeholder="请选择您要预约的设备"
							:options="deviceNameOptions"
							:disabled="!formData.reservationDate || !formData.timeSlot || !formData.typeId"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="预约用户名：" name="userName">
						<a-input v-model:value="formData.userName" placeholder="请输入预约用户名" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="使用目的：" name="purpose">
						<a-input v-model:value="formData.purpose" placeholder="请输入使用目的" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="备注：" name="remark">
						<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="deviceReservationForm">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import deviceReservationApi from '@/api/biz/deviceReservationApi'
	import deviceInfoApi from '@/api/biz/deviceInfoApi'
	import bizDictApi from '@/api/biz/bizDictApi'
	import deviceTimeApi from '@/api/biz/deviceTimeApi'
	import { message } from 'ant-design-vue'
	import dayjs from 'dayjs'
	import deviceTypeApi from '@/api/biz/deviceTypeApi'
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const typeOptions = ref([])
	const allTimeSlots = ref([])
	const timeSlotOptions = ref([])
	const deviceNameOptions = ref([])

	// 处理日期变化
	const handleDateChange = () => {
		// 更新时间段选项
		if (formData.value.typeId) {
			updateDisplayedTimeSlots()
		}

		// 更新设备选项
		if (formData.value.typeId && formData.value.timeSlot) {
			updateDeviceOptions()
		} else {
			deviceNameOptions.value = []
			formData.value.deviceName = undefined
		}
	}
	// 处理设备类型变化
	const handleTypeChange = async () => {
		formData.value.timeSlot = undefined
		formData.value.deviceName = undefined
		timeSlotOptions.value = []
		deviceNameOptions.value = []

		if (formData.value.typeId) {
			// 先获取时间段数据
			await getTimeByType(formData.value.typeId)
			// 然后更新显示的时间段选项
			if (formData.value.reservationDate) {
				updateDisplayedTimeSlots()
			} else {
				timeSlotOptions.value = [...allTimeSlots.value]
			}
		}
	}
	// 处理时间段变化
	const handleTimeSlotChange = () => {
		formData.value.deviceName = undefined
		if (formData.value.reservationDate && formData.value.timeSlot && formData.value.typeId) {
			updateDeviceOptions()
		} else {
			deviceNameOptions.value = []
		}
	}

	// 获取设备类型
	const getType = () => {
		deviceTypeApi.getAll().then((res) => {
			typeOptions.value = res.map((orgNode) => {
				const groupOption = {
					label: orgNode.name,
					disabled: true, // 禁用机构节点
					style: {
						fontWeight: 'bold',
						backgroundColor: '#f5f5f5'
					},
					options: []
				}
				if (orgNode.children && orgNode.children.length > 0) {
					groupOption.options = orgNode.children.map((typeNode) => ({
						label: typeNode.name,
						value: typeNode.id,
						disabled: false
					}))
				}

				return groupOption
			})
		})
	}

	// 根据设备类型获取时间段
	const getTimeByType = async (typeId) => {
		try {
			const res = await deviceTimeApi.getDeviceTimeByType({ id: typeId })
			if (res && res.length > 0) {
				allTimeSlots.value = res.map((item) => ({
					label: item,
					value: item
				}))
			} else {
				allTimeSlots.value = []
			}
			return allTimeSlots.value
		} catch (error) {
			console.error('获取时间段失败:', error)
			allTimeSlots.value = []
			return []
		}
	}

	// 更新显示的时间段选项
	const updateDisplayedTimeSlots = () => {
		if (!allTimeSlots.value.length) {
			timeSlotOptions.value = []
			return
		}

		if (!formData.value.reservationDate) {
			timeSlotOptions.value = [...allTimeSlots.value]
			return
		}

		const selectedDate = dayjs(formData.value.reservationDate).startOf('day')
		const today = dayjs().startOf('day')

		if (selectedDate.isSame(today, 'day')) {
			// 如果选择的是今天
			const now = dayjs() // 获取当前精确时间
			timeSlotOptions.value = allTimeSlots.value.filter((slot) => {
				const startTimeStr = slot.value.split('-')[0]
				const [hour, minute] = startTimeStr.split(':').map(Number)
				// 构建该时间段在今天的开始时间点
				const slotStartDateTime = dayjs().hour(hour).minute(minute).second(0).millisecond(0)
				return now.isBefore(slotStartDateTime)
			})

			// 检查当前已选的时间段是否仍然有效
			if (formData.value.timeSlot) {
				const isCurrentSlotStillAvailable = timeSlotOptions.value.some(
					(option) => option.value === formData.value.timeSlot
				)
				if (!isCurrentSlotStillAvailable) {
					formData.value.timeSlot = undefined
					message.warning('原选择的时间段已过或不可用，请重新选择。')
					deviceNameOptions.value = []
					formData.value.deviceName = undefined
				}
			}
		} else {
			timeSlotOptions.value = [...allTimeSlots.value]
		}
	}

	// 更新设备选项，标记已预约的设备
	const updateDeviceOptions = () => {
		if (!formData.value.typeId || !formData.value.reservationDate || !formData.value.timeSlot) {
			return
		}

		const params = {
			typeId: formData.value.typeId,
			reservationDate: formData.value.reservationDate,
			timeSlot: formData.value.timeSlot,
			id: formData.value.id || ''
		}

		// 先获取该类型的所有设备
		deviceInfoApi
			.deviceInfoListByType({ type: formData.value.typeId })
			.then((allDevices) => {
				if (allDevices && allDevices.length > 0) {
					deviceReservationApi
						.getReservedDevices(params)
						.then((reservedDevices) => {
							if (reservedDevices && reservedDevices.length > 0) {
								// 更新设备选项，禁用已预约的设备
								deviceNameOptions.value = allDevices.map((device) => {
									const isReserved = reservedDevices.includes(device.id)
									return {
										label: device.name + (isReserved ? ' (已预约)' : ''),
										value: device.name,
										deviceId: device.id,
										disabled: isReserved
									}
								})

								if (
									!formData.value.id &&
									formData.value.deviceName &&
									reservedDevices.includes(formData.value.deviceName)
								) {
									formData.value.deviceName = undefined
									message.warning('该设备在所选时间段已被预约，请重新选择')
								}
							} else {
								deviceNameOptions.value = allDevices.map((device) => {
									return {
										label: device.name,
										value: device.name,
										deviceId: device.id
									}
								})
							}
						})
						.catch(() => {})
				} else {
					deviceNameOptions.value = []
				}
			})
			.catch(() => {})
	}

	// 日期禁用
	const disabledDate = (current) => {
		const today = dayjs().startOf('day')
		const windows = today.add(7, 'days').startOf('day')

		if (current.isBefore(today)) {
			return true
		}
		if (current.isAfter(windows)) {
			return true // 2. 禁用从今天起7天之后的日期 (即晚于 today.add(6, 'days'))
		}
		const dayOfWeek = current.day()
		if (dayOfWeek === 0 || dayOfWeek === 6) {
			return true // 如果是周日 (0) 或 周六 (6)，则禁用
		}
		return false
	}

	// 打开抽屉
	const onOpen = (record) => {
		open.value = true
		// 重置/初始化状态
		formData.value = {}
		allTimeSlots.value = []
		timeSlotOptions.value = []
		deviceNameOptions.value = []
		typeOptions.value = getType()

		if (record) {
			// 编辑模式
			formData.value = cloneDeep(record)
		} else {
			// 新增模式
			const userInfo = tool.data.get('USER_INFO')
			if (userInfo && userInfo.name) {
				formData.value.userName = userInfo.name
			}
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}

	// 默认要校验的
	const formRules = {
		typeId: [required('请选择设备类型')],
		deviceName: [required('请选择设备名称')],
		userName: [required('请输入预约用户名')],
		reservationDate: [required('请选择预约日期')],
		timeSlot: [required('请选择预约时间段')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				// 默认开启自动审核
				if (true) {
					formDataParam.status = '已批准'
					formDataParam.approverName = '自动审核'
					formDataParam.approverTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
					formDataParam.approvalRemark = '已批准'
				} else {
					formDataParam.status = '待审核'
				}
				deviceReservationApi
					.deviceReservationSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}

	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
